//
//  BookChapterService.m
//  readNovels
//
//  Created by 吳瀾洲 on 2020/4/28.
//  Copyright © 2020 wulanzhou. All rights reserved.
//

#import "BookChapterService.h"
#import <AFNetworking/AFNetworking.h>
#import <TFHpple/TFHpple.h>
#import "NSString+CZExtend.h"
#import "ChapterDBService.h"

#define kBookChapterDomain @"com.download.chapter.dom"
#define kBookChapterParamErrorCode       6000  //参数错误
#define kBookChapterParamErrorMsg        @"参数错误"  //参数错误

#define kBookChildChapterErrorCode       6001
#define kBookChildChapterErrorMsg        @"下载子章节失败"

@interface BookChapterService()

@property (nonatomic,assign) BOOL  isFinished; //是否下载完成
@property (nonatomic,assign) BOOL  isDecodeMultChapter; //是否解析多章节
@property (nonatomic,strong) NSMutableArray <NSString *> *allContent; //所有内容
@property (nonatomic,strong) ChapterDBService *dbService;

@end

@implementation BookChapterService

- (instancetype)init{

    if (self = [super init]) {
        self.isFinished = NO;
        self.isDecodeMultChapter = YES;
        self.allContent = [NSMutableArray arrayWithCapacity:0];
    }
    return self;
}

- (ChapterDBService *)dbService{

    if (!_dbService) {
        _dbService = [[ChapterDBService alloc] init];
    }
    return _dbService;
}


- (void)asyncChapter{
    if (self.catalog && self.catalog.page_url && [self.catalog.page_url length]>0) {
        
        
        __block BookChapterService *WSELF = self;
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 120.0f;
        [manager GET:self.catalog.page_url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            WSELF.isFinished = YES;
            //解析html
            [WSELF decodeHtmlData:responseObject];
            
            //下载子章节
            //[WSELF downloadChildChapters];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            WSELF.isFinished = NO;
            //NSLog(@"请求失败= %@",error);
            if (WSELF.chapterFinishedBlock) {
                WSELF.chapterFinishedBlock(NO,error);
            }
            [WSELF updateDBSuccess:NO content:@""];
        }];
    }else{
    
        if (self.chapterFinishedBlock) {
            self.chapterFinishedBlock(NO,[self errorCode:kBookChapterParamErrorCode message:kBookChapterParamErrorMsg]);
        }
        [self updateDBSuccess:NO content:@""];
    }
}
#pragma 私有方法
- (void)decodeHtmlData:(NSData *)htmlData{
    
   
    //__block BookChapter *WSELF = self;
    
    //TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:htmlData encoding:@"utf-8"]; //GBK
    TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:htmlData encoding:self.chapterHpple.encoding]; //GBK
    //NSArray * elements  = [doc searchWithXPathQuery:@"//div[@id='htmlContent']"];
    NSArray * elements  = [doc searchWithXPathQuery:self.chapterHpple.xpath];
    
    //解析文章内容
    if (elements && [elements count] > 0) {
        TFHppleElement *elem = [elements objectAtIndex:0];
        
        NSMutableString *content = [NSMutableString stringWithString:@""];
        [elem.children enumerateObjectsUsingBlock:^(TFHppleElement *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (![obj.content isEmpty]) {
                [content appendString:obj.content];
            }
        }];
        [self.allContent addObject:[content Trim]];
    }else{
        NSLog(@"解析失败!");
        if (self.chapterFinishedBlock) {
            self.chapterFinishedBlock(NO,[self errorCode:400 message:@"html解析失败"]);
        }
        [self updateDBSuccess:NO content:@""];
        return;
    }
    
    //下载子章节
    BookChapterService *childBook = [self getNextChildChapter:doc];
    if (childBook) {
        [self downloadMultChildChapter:childBook];
    }else{ //下载完成
        [self save];
        if (self.chapterFinishedBlock) {
            self.chapterFinishedBlock(YES,nil);
        }
    }
    
}

//获取下一页
- (BookChapterService *)getNextChildChapter:(TFHpple *)doc{
     // __block BookChapterService *WSELF = self;

    //NSArray * elements  = [doc searchWithXPathQuery:@"//a[@id='linkNext']"];
    NSArray * elements  = [doc searchWithXPathQuery:self.chapterHpple.childXPathQuery];
       if (elements && [elements count] > 0) {
          TFHppleElement *elem = [elements objectAtIndex:0];
           if ([elem.content isEqualToString:@"下一页"]) {
               BookChapterService *entity = [[BookChapterService alloc] init];
               entity.catalog = self.catalog;
               entity.chapterHpple = self.chapterHpple;
               
               if (self.chapterHpple.loopChapterBlock) {
                   self.chapterHpple.loopChapterBlock(entity.catalog, elem);
               }
               //entity.pageUrl =[NSString stringWithFormat:@"http://www.630kan.com/book/20894/%@",[elem.attributes objectForKey:@"href"]]; //
               //NSLog(@"下一章节url =%@",entity.pageUrl);
               return entity;
           }
       }
       return nil;
}


//下载子章节
- (void)downloadMultChildChapter:(BookChapterService *)entity{
    
    __block BookChapterService *WSELF = self;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 120.0f;
    [manager GET:entity.catalog.page_url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [WSELF decodeHtmlData:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"下载子章节失败,title=%@,url= %@",entity.catalog.name,entity.catalog.page_url);
        if (WSELF.chapterFinishedBlock) {
            WSELF.chapterFinishedBlock(NO,error);
        }
        [WSELF updateDBSuccess:NO content:@""];
    }];
}

- (void)updateDBSuccess:(BOOL)success content:(NSString *)message{

    
    //保存数据库
    if(self.catalog){
        
        Chapter *entity = [self.dbService Entity:[NSNumber numberWithInteger:self.catalog.cId]];
        if(entity){ //修改
            
            entity.content = message;
            entity.finished = success;
            entity.mtime = [NSDate date];
            [self.dbService Update:entity];
            
        }else{ //新增
            
            Chapter *item = [[Chapter alloc] init];
            item.catalog_id = self.catalog.cId;
            item.title = self.catalog.name;
            item.content = message;
            item.finished = success;
            item.sort = self.catalog.sort;
            item.ctime = [NSDate date];
            item.mtime = [NSDate date];
            [self.dbService Insert:item];
        }
        
    }

}
- (NSError *)errorCode:(NSInteger)code message:(NSString *)msg{
    
    NSDictionary *dic=@{@"code":[NSNumber numberWithInteger:code],@"error":msg};
    NSError *error = [NSError errorWithDomain:kBookChapterDomain code:code userInfo:dic];
    
    return error;
}

- (void)save{
    
    if ( self.allContent && [self.allContent count]>0) {
        
        NSMutableString *allContentStr = [NSMutableString stringWithString:@""];
        [self.allContent enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [allContentStr appendString:[obj TrimAll]];
        }];
        //保存数据库
        [self updateDBSuccess:YES content:allContentStr];
        
        //[allContents writeToFile:[[BookDir shareInstance] fileNameToPath:[NSString stringWithFormat:@"%d.%@.txt",self.chapterIndex,self.title]] atomically:NO encoding:NSUTF8StringEncoding error:nil];
        
        /**
        [CZMyLog writeLog:allContents path:[[BookDir shareInstance] fileNameToPath:[NSString stringWithFormat:@"%d.%@.txt",self.chapterIndex,self.title]]];
         **/
       // NSLog(@"章节：%@写入成功",self.title);
        
        return;
    }
    NSLog(@"章节：%@写入失败，地址为:%@",self.catalog.name,self.catalog.page_url);
}

@end
